package controller

import (
	"encoding/base64"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"roc/wechat/controller/resp"
	"roc/wechat/global"
	"roc/wechat/models/request"
	"roc/wechat/utils"
)

type AuthController struct{}

// CreateAuthCode
// @Description 生成编码
// @Success 200 {string} string "获取成功"
// @Router /auth/auth_code [post]
func (a *AuthController) CreateAuthCode(c *gin.Context) {
	var req request.CreateAuthCodeReq
	err := c.Bind(&req)
	if err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			resp.FailData("参数解析失败", "Err:"+err.Error(), c)
			return
		}
		resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
		return
	}

	prefix := map[int]string{
		utils.SOURCE_CRM_FLAG: utils.CACHE_ETA_AUTH_CODE_PREFIX,
		utils.SOURCE_ETA_FLAG: utils.CACHE_CRM_AUTH_CODE_PREFIX,
	}
	str := base64.URLEncoding.EncodeToString([]byte(req.AdminName))
	key := fmt.Sprint(prefix[req.Source], str)

	// 是否已生成但未消费
	exist, _ := global.Rc.RedisString(key)
	if exist != "" {
		resp.OkData("获取成功", str, c)
		return
	}
	if global.Rc.SetNX(key, req.AdminName, utils.GetTodayLastSecond()) {
		resp.OkData("获取成功", str, c)
		return
	}
	return
}
